<script setup lang="ts">
import { nextTick, reactive, ref, useTemplateRef } from 'vue';
import { useBoolean } from '@sa/hooks';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { fetchIsCaptchaEnable } from '@/service/api';
import ActionVerify from '@/components/common/verifition/verify.vue';
import Title from '@/components/common/login/auth-title.vue';
import { localStg } from '@/utils/storage';

defineOptions({
  name: 'PwdLogin'
});

interface Emit {
  (event: 'changeModule', module: UnionKey.LoginModule): void;
}
const emit = defineEmits<Emit>();

const authStore = useAuthStore();

const { formRef, validate } = useNaiveForm();

interface FormModel {
  mobile: string;
  password: string;
}

const model: FormModel = reactive({
  mobile: import.meta.env.VITE_LOGIN_ACCOUNT || '',
  password: import.meta.env.VITE_LOGIN_PWD || ''
});

const { bool: verifiction, setBool: setVerifiction } = useBoolean();

const { formRules, createRequiredRule } = useFormRules();
type RuleKey = Extract<keyof FormModel, 'mobile' | 'password'>;

const rules: Record<RuleKey, CommonType.WithArray<App.Global.FormRule>> = {
  mobile: formRules.phone,
  password: [createRequiredRule('请输入密码')]
};

const verifyRef = useTemplateRef('verifyRef');

async function handleSubmit() {
  await validate();
  const { data: enable, error } = await fetchIsCaptchaEnable({ mobile: model.mobile });
  if (error) return;
  if (enable) {
    setVerifiction(true);
    await nextTick();
    verifyRef.value?.show();
  } else {
    passwordLogin();
  }
}

/** 验证码成功后的code */
const captchaVerification = ref();
/** 行为验证码成功回调：返回的二次验证参数, 和登录参数一起回传给登录接口，方便后台进行二次验证 */
function success({ code }: CommonType.RecordObject) {
  captchaVerification.value = code;
  passwordLogin();
}

/** 记住账号 */
const REMEMBER_ME_KEY = 'rememberMe';
const localUsername = localStg.get(REMEMBER_ME_KEY) || '';
const rememberMe = ref(Boolean(localUsername));

/** 口令登录 */
async function passwordLogin() {
  const params: LoginApi.LoginParams = {
    mobile: model.mobile,
    password: model.password
  };
  if (captchaVerification.value) {
    params.captchaVerification = captchaVerification.value;
  }
  await authStore.login(params);
  /** 记住账号 */
  localStg.set(REMEMBER_ME_KEY, rememberMe.value ? model.mobile : '');
  /** 重置验证码信息 */
  captchaVerification.value = null;
}

function handleChangeModule(module: UnionKey.LoginModule) {
  emit('changeModule', module);
}
</script>

<template>
  <div @keydown.enter.prevent="handleSubmit">
    <Title title="欢迎回来 👋🏻">
      <template #desc>
        <span class="text-muted-foreground">请输入您的账户信息以开始管理您的项目</span>
      </template>
    </Title>

    <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
      <NFormItem path="mobile">
        <NInput v-model:value="model.mobile" placeholder="请输入用户名" />
      </NFormItem>
      <NFormItem path="password">
        <NInput
          v-model:value="model.password"
          type="password"
          show-password-on="click"
          placeholder="请输入密码"
          :input-props="{ autocomplete: 'off' }"
        />
      </NFormItem>
    </NForm>

    <div class="mb-6 flex justify-between">
      <NCheckbox v-model:checked="rememberMe">记住账号</NCheckbox>
      <NButton
        v-if="false"
        type="primary"
        text
        tag="a"
        class="text-sm font-normal"
        @click="handleChangeModule('forget-password')"
      >
        忘记密码？
      </NButton>
    </div>
    <NButton type="primary" block :loading="authStore.loginLoading" @click="handleSubmit">登录</NButton>

    <div v-if="false" class="mb-2 mt-4 flex items-center justify-between gap-x-4">
      <NButton class="flex-1" block @click="handleChangeModule('code-login')">手机号登录</NButton>
      <NButton class="flex-1" @click="handleChangeModule('qrcode-login')">扫码登录</NButton>
    </div>

    <div v-if="false" class="mt-32px text-center text-sm">
      还没有账号？
      <NButton type="primary" text tag="a" class="text-sm font-normal" @click="handleChangeModule('register')">
        创建账号
      </NButton>
    </div>
    <Teleport to="body">
      <!-- 验证码 -->
      <ActionVerify
        v-if="verifiction"
        ref="verifyRef"
        mode="pop"
        captcha-type="blockPuzzle"
        :img-size="{ width: '330px', height: '155px' }"
        @success="success"
      ></ActionVerify>
    </Teleport>
  </div>
</template>

<style lang="scss" scoped></style>
